package io.aicn.lowcode.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * SQL执行工具类
 * 用于执行数据库管理模块的建表脚本
 */
@Component
public class SqlExecutor implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        // 检查是否需要执行建表脚本
        if (args.length > 0 && "init-dbmanager".equals(args[0])) {
            executeSqlFile();
        }
    }

    private void executeSqlFile() {
        try {
            // 读取SQL文件
            File sqlFile = new File("create_dbmanager_tables.sql");
            if (!sqlFile.exists()) {
                System.out.println("SQL文件不存在: " + sqlFile.getAbsolutePath());
                return;
            }

            StringBuilder sqlContent = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(sqlFile, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    sqlContent.append(line).append("\n");
                }
            }

            // 分割SQL语句（以分号分隔）
            String[] sqlStatements = sqlContent.toString().split(";");
            
            System.out.println("开始执行数据库管理模块建表脚本...");
            
            for (String sql : sqlStatements) {
                sql = sql.trim();
                if (!sql.isEmpty() && !sql.startsWith("--")) {
                    try {
                        jdbcTemplate.execute(sql);
                        System.out.println("执行成功: " + sql.substring(0, Math.min(50, sql.length())) + "...");
                    } catch (Exception e) {
                        System.err.println("执行失败: " + sql.substring(0, Math.min(50, sql.length())) + "...");
                        System.err.println("错误信息: " + e.getMessage());
                    }
                }
            }
            
            System.out.println("数据库管理模块建表脚本执行完成！");
            
        } catch (Exception e) {
            System.err.println("执行SQL脚本时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}